/**
 * 组件自适应
 * 
 */
import { addListener, removeListener } from 'resize-detector';

function debounce (delay, callback) {
    let lastTime;

    return function () {
        clearTimeout(lastTime);

        const [that, args] = [this, arguments];

        lastTime = setTimeout(() => {
            callback.apply(that, args)
        }, delay);
    }
}

export default {

    mounted () {
        const { handleResize, resizeDebounce = 100 } = this;
        this.__resizeHandler = debounce(resizeDebounce, () => {
            if (typeof handleResize === 'function') handleResize();
        });

        this.$nextTick(() => {
            addListener(this.$el, this.__resizeHandler);
        });
    },

    beforeDestroy () {
        removeListener(this.$el, this.__resizeHandler);
    }
}
